<template>
    <div class="video-list">
        <a-tabs class="top-tab" v-model:activeKey="deptActiveKey" @change="handleTab">
            <a-tab-pane v-for="item in deptList" :key="item.value" :tab="item.label"
                :disabled="userStore.getLoginInfo?.userInfo?.orgCode != item.value">
            </a-tab-pane>
            <template #rightExtra>
                <a-select :options="seatList" style="width: 150px;margin-right: 10px;"
                    v-model:value="seatValue"></a-select>
                <a-date-picker v-model:value="dayValue" style="width: 150px;margin-right: 10px;" />
                <a-button type="primary" @click="handleSearch">查询</a-button>
            </template>
        </a-tabs>
        <div class="video-flex">

            <VideoContent class="video-flex-item" :rootId="item.rootId + index" v-for="item, index in caremaList" :videoId="item.videoId + index"
                :canvasId="item.canvasId + index" :startTime="item.startTime" :name="item.name"
                :caramObj="item.caramObj" :deviceObj="item.deviceObj" :hasTitle="item.hasTitle"
                :hasAction="item.hasAction" :cameraPlaybackObj="item.cameraPlaybackObj" :history="true"></VideoContent>
            <a-result v-if="caremaList.length == 0" style="flex:1">
                <template #icon>
                    <img :src="notDataSvg" width="150px" height="150px">
                </template>
            </a-result>
        </div>
        <!-- <div style="text-align: right;margin-top: 20px;">
            <a-pagination v-model:current="current" :total="total" :pageSize="pageSize" @change="handlerPageChange" />
        </div> -->
    </div>
</template>
<script setup>

import { onMounted, ref, unref, onUnmounted } from 'vue'
import VideoContent from './components/VideoContent.vue'
import { listAll, list, diviceList } from './videolist.api';
import { useUserStore } from '/@/store/modules/user';
import { message, Pagination } from 'ant-design-vue';
import dayjs from 'dayjs';
import NvrRpc from './rpc.js'
import notDataSvg from '/@/assets/svg/no-data.svg';
const APagination = Pagination;
const userStore = useUserStore();
let isLogin = ref(false);//nvr是否登录
let deptActiveKey = ref('');
let deptList = ref([])//部门
let current = ref(1);
let total = ref(0);
let pageSize = ref(1000);
let today = dayjs().format();
console.log(today, "today===")
let dayValue = ref(dayjs(dayjs().format(), 'YYYY-MM-DD'));//回放日期
let deviceObj = {
    ip: '',
    username: '',
    password: '',
    port: ''
}//设备nvr的信息
const videoList = ref([])
const seatList = ref([])
let seatValue = ref();//下拉的数据
const caremaList = ref([]);//录像片段数组
const handleTab = () => {
    if (isLogin.value) {
        querySeatList();
    }
}
const getDeptList = async () => {
    let result = await listAll();
    result = result.filter(item => {
        return item.izLeaf != 0
    })
    let data = result.map(item => {
        if (item.izLeaf != 0) {
            return {
                label: item.departName,
                value: item.orgCode
            }
        }
    })
    if (data.length > 0) {
        let obj = data.find(item => {
            return item.value == userStore.getLoginInfo?.userInfo?.orgCode
        })
        console.log("登录回来的数据", obj)
        if (obj) {
            deptActiveKey.value = obj.value;
        } else {
            deptActiveKey.value = data[0].value;
        }
    }
    deptList.value = data;
}
/**
 * 查询当前部门的席位，不分页
 */
const querySeatList = async () => {
    videoList.value = []
    seatList.value = []
    caremaList.value = []
    let result = await list({
        pageNo: current.value,
        pageSize: pageSize.value,
        orgCode: deptActiveKey.value,
        disable: '0'
    });
    if (result.records && result.records.length > 0) {
        result.records.filter(item => {
            return !item.equipment;
        })
        let data = result.records.map(item => {
            return {
                name: item.name,
                label: item.name,
                value: item.id,
                rootId:'rootId',
                videoId: 'videoId',
                canvasId: 'canvasId',
                caramObj: {
                    ip: item.equipment.ip,
                    port: item.equipment.port,
                    username: item.equipment.username,
                    password: item.equipment.password,
                },
                deviceObj: deviceObj,
                hasAction: true,
                hasTitle: true,
                startTime: dayValue.value,// dayValue.value
            }
        })


        videoList.value = data;
        seatList.value = data;
        if (data.length > 0) {
            seatValue.value = data[0].value;
        }
        total.value = result.total;
        handleSearch()
        console.log("dsds-----", videoList.value);
    }
}
/**
 * 获取NVR的配置
 */
const getDiviceList = async () => {

    let result = await diviceList({
        category: 'dvr'
    });
    if (result.records && result.records.length > 0) {
        deviceObj = {
            ip: result.records[0].ip,
            port: result.records[0].port,
            username: result.records[0].username,
            password: result.records[0].password
        }
        querySeatList()
    }
}

/**
 * 执行查询席位的录像回放片段。
 */
const handleSearch = async () => {
    if(!dayValue.value){
        message.warning("请先选择日期！");
        return false;
    }
    if (isLogin.value) {
        getCameraAll();
    }else{
        try {
        let result = await NvrRpc.logIn({
                ip: deviceObj.ip,
                port: deviceObj.port,
                username: deviceObj.username,
                password: deviceObj.password
            })
            isLogin.value = result?.result;
            getCameraAll();
        } catch (error) {
            isLogin.value = false;
        }
    }

}
/**
 * 获取所有的通道，码流
 */
const getCameraAll = () => {
    let obj = seatList.value.find(o => {
        return o.value == seatValue.value
    })
    let startTime = dayjs(dayValue.value).format('YYYY-MM-DD') + ' 00:00:00';
    let endTime = dayjs(dayValue.value).format('YYYY-MM-DD') + ' 23:59:59';
    if (obj) {
        caremaList.value = [];
        NvrRpc.getCameraAll().then(res => {
            if (res && res.length > 0) {
                for (const item of res) {
                    if (item.DeviceInfo && item.DeviceInfo.Address == obj.caramObj.ip && item.Enable) {
                        searchRecord({ cameraChannel: item.UniqueChannel, startTime, endTime })
                    }
                }
            }
        })
    }

}
const fileSizeFn = (size) => {
    let mb = size / 1024 / 1024;
    if (mb < 1) {
        return (size / 1024).toFixed(2) + ' KB'
    } else {
        return (mb).toFixed(2) + ' MB'
    }
}
const searchRecord = (params) => {
    console.log("进来了");
    
    caremaList.value = [];
    let obj = seatList.value.find(o => {
        return o.value == seatValue.value
    })
    NvrRpc.searchRecord(params).then(res => {
        let data = res.map((item, index) => {
            return {
                name: dayjs(item.StartTime).format('HH:mm:ss') + ' - ' + dayjs(item.EndTime).format('HH:mm:ss') + " | " + fileSizeFn(item.Length),
                videoId: 'videoId',
                rootId:'rootId',
                canvasId: 'canvasId',
                caramObj: {
                    ip: obj.ip,
                    port: obj.port,
                    username: obj.username,
                    password: obj.password,
                },
                deviceObj: deviceObj,
                hasAction: true,
                hasTitle: true,
                cameraPlaybackObj: { ...item, ...{ playbackIndex: index,time:0,violationTime:item.StartTime } },
            }
        })
        caremaList.value = data;
        console.log("成功：：", data)

    }).catch(err => {
        console.log("异常：：", err)
    })
}
onMounted(async () => {
    await getDeptList();
    await getDiviceList();
    try {
        let result = await NvrRpc.logIn({
            ip: deviceObj.ip,
            port: deviceObj.port,
            username: deviceObj.username,
            password: deviceObj.password
        })
        isLogin.value = result?.result;
    } catch (error) {
        isLogin.value = false;
    }
})
onUnmounted(() => {

    try {
        console.log("父组件销毁");

        caremaList.value = [];
        NvrRpc.logOut();
    } catch (error) {

    }

})
</script>
<style lang="less" scoped>
.video-list {
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: #fff;

    .video-flex {
        position: relative;
        width: 100%;
        height: auto;
        display: flex;
        gap: 20px;

        justify-content: flex-start;
        flex-wrap: wrap;

        &-item {
            position: relative;

            width: 32%;
            height: 300px;
        }
    }
}
</style>